//
//  JMHomeViewController.m
//  OpenSesame
//
//  Created by zhangjiaming on 15/12/21.
//  Copyright © 2015年 OpenSesame. All rights reserved.
//

#import "JMHomeViewController.h"
#import "JMCarKeyViewController.h"
#import "WDCarViewController.h"
#import "JMFrequencyViewController.h"
#import "JMRegenerationController.h"
#import "JMInstructionController.h"
#import "JMTabBarController.h"
#import "JMCenterManager.h"
#import "JMCrc16.h"
#import "JMPeripheralView.h"
#import "MBProgressHUD+JM.h"
#import "JMPeripheralCell.h"

@interface JMHomeViewController () <UIAlertViewDelegate, UITabBarControllerDelegate, JMTabBarControllerDelegate, JMCenterManagerDelegate, JMPeripheralViewDelegate, UITableViewDelegate, UITableViewDataSource>
@property (weak, nonatomic) UIButton *doorControlBtn;
@property (weak, nonatomic) UIButton *promixityBtn;
@property (weak, nonatomic) UIView *rightView;
@property (weak, nonatomic) UIView *promixityRightView;
@property (weak, nonatomic) UIButton *yelloBtn;
@property (weak, nonatomic) UIButton *bluetoothBtn;

@property (strong, nonatomic) UIView *shieldView;
@property (strong, nonatomic) NSMutableArray *peripherals; // 存放扫描到得外设对象
@property (strong, nonatomic) JMPeripheralView *peripheralView;
@property (strong, nonatomic) JMCenterManager *mgrs;
@property (weak, nonatomic) UIImageView *connectView; // 正在连接view
@property (strong, nonatomic) CBPeripheral *peripheral; // 连接的外设
@end

@implementation JMHomeViewController
- (NSMutableArray *)peripherals {
    if (!_peripherals) {
        _peripherals = [NSMutableArray array];
    }
    return _peripherals;
}

- (UIView *)shieldView {
    if (!_shieldView) {
        _shieldView = [[UIView alloc] init];
        _shieldView.frame = CGRectMake(0, 0, JMPhoneWidth, JMPhoneHeight);
        _shieldView.backgroundColor = [UIColor blackColor];
        _shieldView.alpha = 0.7;
    }
    return _shieldView;
}

- (JMPeripheralView *)peripheralView {
    if (!_peripheralView) {
        _peripheralView = [[JMPeripheralView alloc] initWithFrame:CGRectMake(30, JMPhoneHeight * 0.25, JMPhoneWidth - 60, JMPhoneHeight * 0.5)];
        _peripheralView.tableView.delegate = self;
        _peripheralView.tableView.dataSource = self;
        _peripheralView.delegate = self;
    }
    return _peripheralView;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 初始化界面
    [self setUpinterface];
    
    // 初始化中心设备管理类
    JMCenterManager *mgs = [JMCenterManager sharedCenterManager];
    self.mgrs = mgs;
    if (mgs.opened) { // 蓝牙打开
        self.yelloBtn.hidden = YES;
    } else {
        self.yelloBtn.hidden = NO;
    }
    mgs.delegate = self;
}

/**
 *  初始化界面
 */
- (void)setUpinterface {
    // 设置导航栏右侧内容
    UIButton* btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = CGRectMake(0, 0, 60, 44);
    [btn setImage:[UIImage imageNamed:@"蓝牙 未连"] forState:UIControlStateNormal];
    [btn setImage:[UIImage imageNamed:@"蓝牙 按下"] forState:UIControlStateHighlighted];
    [btn setImage:[UIImage imageNamed:@"蓝牙"] forState:UIControlStateSelected];
    [btn addTarget:self action:@selector(scanBlueTooth) forControlEvents:UIControlEventTouchUpInside];
    btn.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, -25);
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
    self.bluetoothBtn = btn;
    
    // 设置顶部topImageView
    UIImageView *topImageView = [[UIImageView alloc] init];
    [self.view addSubview:topImageView];
    CGFloat topRatio = 0;// 图片宽高比
    if (JMPhoneWidth > 375) { // 6p;
        topRatio = 1242/650.0;
        topImageView.image = [UIImage imageNamed:@"BANNER6p"];
    } else if (JMPhoneWidth > 320) { // 6
        topRatio = 15/8.0;
        topImageView.image = [UIImage imageNamed:@"BANNER6"];
    } else { // 4s,5
        topRatio = 640.0/260.0;
        topImageView.image = [UIImage imageNamed:@"BANNER4"];
    }
    topImageView.frame = CGRectMake(0, 64, JMPhoneWidth, JMPhoneWidth/topRatio);
    
    // 设置汽车钥匙按钮
    UIButton *carKeybtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:carKeybtn];
    CGFloat carRatio = 0; // 图片宽高比
    if (JMPhoneWidth > 375) { // 6p;
        carRatio = 591/1170.0;
        [carKeybtn setImage:[UIImage imageNamed:@"汽车钥匙6p"] forState:UIControlStateNormal];
        [carKeybtn setImage:[UIImage imageNamed:@"汽车钥匙 按下6p"] forState:UIControlStateHighlighted];
    } else if (JMPhoneWidth > 320) { // 6
        carRatio = 345/658.0;
        [carKeybtn setImage:[UIImage imageNamed:@"汽车钥匙6"] forState:UIControlStateNormal];
        [carKeybtn setImage:[UIImage imageNamed:@"汽车钥匙 按下6"] forState:UIControlStateHighlighted];
    } else { // 4s,5
        carRatio = 291.0/424.0;
        [carKeybtn setImage:[UIImage imageNamed:@"汽车钥匙4"] forState:UIControlStateNormal];
        [carKeybtn setImage:[UIImage imageNamed:@"汽车钥匙 按下4"] forState:UIControlStateHighlighted];
    }
    
    carKeybtn.y = topImageView.y + topImageView.height + 12;
    carKeybtn.x = 10;
    carKeybtn.width = (JMPhoneWidth - 30) * 0.5;
    carKeybtn.height = carKeybtn.width/carRatio;
    [carKeybtn addTarget:self action:@selector(carKeyBtnClick) forControlEvents:UIControlEventTouchUpInside];

    // 设置电动门遥控按钮
    UIButton *doorControlBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.doorControlBtn = doorControlBtn;
    [self.view addSubview:doorControlBtn];
    CGFloat doorRatio = 0; // 图片宽高比
    if (JMPhoneWidth > 375) { // 6p;
        doorRatio = 591/1170.0;
        [doorControlBtn setImage:[UIImage imageNamed:@"电动门6p"] forState:UIControlStateNormal];
        [doorControlBtn setImage:[UIImage imageNamed:@"电动门 按下6p"] forState:UIControlStateHighlighted];
    } else if (JMPhoneWidth > 320) { // 6
        doorRatio = 345/658.0;
        [doorControlBtn setImage:[UIImage imageNamed:@"电动门6"] forState:UIControlStateNormal];
        [doorControlBtn setImage:[UIImage imageNamed:@"电动门 按下6"] forState:UIControlStateHighlighted];
    } else { // 4s,5
        doorRatio = 291.0/424.0;
        [doorControlBtn setImage:[UIImage imageNamed:@"电动门4"] forState:UIControlStateNormal];
        [doorControlBtn setImage:[UIImage imageNamed:@"电动门 按下4"] forState:UIControlStateHighlighted];
    }
    
    doorControlBtn.width = carKeybtn.width;
    doorControlBtn.height = doorControlBtn.width/doorRatio;
    doorControlBtn.y = carKeybtn.y;
    doorControlBtn.x = 10 + carKeybtn.width + carKeybtn.x;
    [doorControlBtn addTarget:self action:@selector(doorBtnClick) forControlEvents:UIControlEventTouchUpInside];
    
    // 设置电动门遥控右边的隐藏控件
    UIView *rightView = [[UIView alloc] init];
    [self.view addSubview:rightView];
    self.rightView = rightView;
    rightView.frame = CGRectMake(JMPhoneWidth, doorControlBtn.y, doorControlBtn.width, doorControlBtn.height);
    rightView.backgroundColor = [UIColor whiteColor];
    
    // 背景
    UIImageView *rightBack = [[UIImageView alloc] init];
    [rightView addSubview:rightBack];
    rightBack.frame = CGRectMake(0, 0, rightView.width, rightView.height);
    
    // 拷贝按钮
    UIButton *copyBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [rightView addSubview:copyBtn];
    copyBtn.frame = CGRectMake(0, 0, rightView.width, rightView.height/3);
    [copyBtn addTarget:self action:@selector(copyBtnClick) forControlEvents:UIControlEventTouchUpInside];
    
    // 再生按钮
    UIButton *regenerateBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [rightView addSubview:regenerateBtn];
    regenerateBtn.frame = CGRectMake(0, copyBtn.height, rightView.width, rightView.height/3);
    [regenerateBtn addTarget:self action:@selector(regenerateBtnClick) forControlEvents:UIControlEventTouchUpInside];
    
    // 测试按钮
    UIButton *testBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [rightView addSubview:testBtn];
    testBtn.frame = CGRectMake(0, copyBtn.height * 2, rightView.width, rightView.height/3);
    [testBtn addTarget:self action:@selector(testBtnClick) forControlEvents:UIControlEventTouchUpInside];
 
    if (JMPhoneWidth > 375) { // 6p;
        rightBack.image = [UIImage imageNamed:@"rightBck16p"];
        [copyBtn setImage:[UIImage imageNamed:@"拷贝6p"] forState:UIControlStateNormal];
        [regenerateBtn setImage:[UIImage imageNamed:@"再生6p"] forState:UIControlStateNormal];
        [testBtn setImage:[UIImage imageNamed:@"测试6p"] forState:UIControlStateNormal];
    } else if (JMPhoneWidth > 320) { // 6
        rightBack.image = [UIImage imageNamed:@"rightBck16"];
        [copyBtn setImage:[UIImage imageNamed:@"拷贝6"] forState:UIControlStateNormal];
        [regenerateBtn setImage:[UIImage imageNamed:@"再生6"] forState:UIControlStateNormal];
        [testBtn setImage:[UIImage imageNamed:@"测试6"] forState:UIControlStateNormal];
    } else { // 4s,5
        rightBack.image = [UIImage imageNamed:@"rightBck14"];
        [copyBtn setImage:[UIImage imageNamed:@"拷贝4"] forState:UIControlStateNormal];
        [regenerateBtn setImage:[UIImage imageNamed:@"再生4"] forState:UIControlStateNormal];
        [testBtn setImage:[UIImage imageNamed:@"测试4"] forState:UIControlStateNormal];
    }
   
    // 设置感应卡
    UIButton *promixityBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.promixityBtn = promixityBtn;
    [self.view addSubview:promixityBtn];
    if (JMPhoneWidth > 375) { // 6p;
        [promixityBtn setImage:[UIImage imageNamed:@"感应卡6p"] forState:UIControlStateNormal];
        [promixityBtn setImage:[UIImage imageNamed:@"感应卡 按下6p"] forState:UIControlStateHighlighted];
    } else if (JMPhoneWidth > 320) { // 6
        [promixityBtn setImage:[UIImage imageNamed:@"感应卡6"] forState:UIControlStateNormal];
        [promixityBtn setImage:[UIImage imageNamed:@"感应卡 按下6"] forState:UIControlStateHighlighted];
    } else { // 4s,5
        [promixityBtn setImage:[UIImage imageNamed:@"感应卡4"] forState:UIControlStateNormal];
        [promixityBtn setImage:[UIImage imageNamed:@"感应卡 按下4"] forState:UIControlStateHighlighted];
    }
    promixityBtn.x = doorControlBtn.x;
    promixityBtn.y = doorControlBtn.y + doorControlBtn.height + 10;
    promixityBtn.width = doorControlBtn.width;
    promixityBtn.height = doorControlBtn.height;
    [promixityBtn addTarget:self action:@selector(promixityBtnClick) forControlEvents:UIControlEventTouchUpInside];
    
    // 设置感应卡右边的隐藏控件
    UIView *promixityRightView = [[UIView alloc] init];
    [self.view addSubview:promixityRightView];
    self.promixityRightView = promixityRightView;
    promixityRightView.frame = CGRectMake(JMPhoneWidth, promixityBtn.y, promixityBtn.width, promixityBtn.height);
    promixityRightView.backgroundColor = [UIColor clearColor];

    // 背景
    UIImageView *rightBack1 = [[UIImageView alloc] init];
    [promixityRightView addSubview:rightBack1];
    rightBack1.frame = CGRectMake(0, 0, promixityRightView.width, promixityRightView.height);
    
    // IC按钮
    UIButton *ICBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [promixityRightView addSubview:ICBtn];
    ICBtn.frame = CGRectMake(0, 0, promixityRightView.width, promixityRightView.height/3);
    [ICBtn addTarget:self action:@selector(ICBtnClick) forControlEvents:UIControlEventTouchUpInside];

    // ID按钮
    UIButton *IDBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [promixityRightView addSubview:IDBtn];
    IDBtn.frame = CGRectMake(0, ICBtn.height, promixityRightView.width, promixityRightView.height/3);
    [IDBtn addTarget:self action:@selector(IDBtnClick) forControlEvents:UIControlEventTouchUpInside];

    // 蓝牙按钮
    UIButton *bluetoothBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [promixityRightView addSubview:bluetoothBtn];
    bluetoothBtn.frame = CGRectMake(0, ICBtn.height * 2, promixityRightView.width, promixityRightView.height/3);
    [bluetoothBtn addTarget:self action:@selector(bluetoothBtnClick) forControlEvents:UIControlEventTouchUpInside];
    
    if (JMPhoneWidth > 375) { // 6p;
        rightBack1.image = [UIImage imageNamed:@"rightBck16p"];
        [ICBtn setImage:[UIImage imageNamed:@"IC6p"] forState:UIControlStateNormal];
        [IDBtn setImage:[UIImage imageNamed:@"ID6p"] forState:UIControlStateNormal];
        [bluetoothBtn setImage:[UIImage imageNamed:@"lanya6p"] forState:UIControlStateNormal];
    } else if (JMPhoneWidth > 320) { // 6
        rightBack1.image = [UIImage imageNamed:@"rightBck16"];
        [ICBtn setImage:[UIImage imageNamed:@"IC6"] forState:UIControlStateNormal];
        [IDBtn setImage:[UIImage imageNamed:@"ID6"] forState:UIControlStateNormal];
        [bluetoothBtn setImage:[UIImage imageNamed:@"lanya6"] forState:UIControlStateNormal];
    } else { // 4s,5
        rightBack1.image = [UIImage imageNamed:@"rightBck14"];
        [ICBtn setImage:[UIImage imageNamed:@"IC4"] forState:UIControlStateNormal];
        [IDBtn setImage:[UIImage imageNamed:@"ID4"] forState:UIControlStateNormal];
        [bluetoothBtn setImage:[UIImage imageNamed:@"lanya4"] forState:UIControlStateNormal];
    }

    // 设置最底部的提示蓝牙连接否的按钮
    UIButton *yelloBtn = [[UIButton alloc] init];
    [self.tabBarController.view addSubview:yelloBtn];
    yelloBtn.hidden = YES;
    yelloBtn.frame = CGRectMake(0, JMPhoneHeight - 49, JMPhoneWidth, 49);
    [yelloBtn setImage:[UIImage imageNamed:@"yello"] forState:UIControlStateNormal];
    [yelloBtn addTarget:self action:@selector(yelloBtnClick) forControlEvents:UIControlEventTouchUpInside];
    self.yelloBtn = yelloBtn;
}

/**
 *  扫描蓝牙
 */
- (void)scanBlueTooth {
    // 添加蒙版
    [self.view addSubview:self.shieldView];
    
    // 添加展示外围设备的View
    [self.view addSubview:self.peripheralView];
    
    // 取出上次记住的外设名称
    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
    NSString *peripheralName = [userDefault objectForKey:@"peripheralName"];
    if (peripheralName) {
        self.peripheralView.lastConncetLabel.text = peripheralName;
    }
    
    // 扫描
    JMCenterManager *mgs = [JMCenterManager sharedCenterManager];
    [mgs beginScan];
}

/**
 *  点击跳转指示操作连接蓝牙页
 */
- (void)yelloBtnClick {
    JMInstructionController *instruction = [[JMInstructionController alloc] init];
    instruction.title = @"帮助说明";
    [self.navigationController pushViewController:instruction animated:YES];
    self.yelloBtn.hidden = YES;
}

/**
 *  点击拷贝按钮
 */
- (void)copyBtnClick {
    // 隐藏控件
    self.rightView.x = JMPhoneWidth;
    
    // 通知代理删除蒙版
    if ([self.delegate respondsToSelector:@selector(homeViewController:willDisPlayHideView:)]) {
        [self.delegate homeViewController:self willDismissHideView:self.promixityRightView];
    }
    
    // 跳转拷贝页面
    JMFrequencyViewController *freVc = [[JMFrequencyViewController alloc] init];
    freVc.title = @"拷贝";
    [self.navigationController pushViewController:freVc animated:YES];
}

/**
 *  点击再生按钮
 */
- (void)regenerateBtnClick {
    // 隐藏控件
    self.rightView.x = JMPhoneWidth;
    
    // 通知代理删除蒙版
    if ([self.delegate respondsToSelector:@selector(homeViewController:willDisPlayHideView:)]) {
        [self.delegate homeViewController:self willDismissHideView:self.promixityRightView];
    }
    
    // 跳转再生页面
    JMRegenerationController *generateVC = [[JMRegenerationController alloc] init];
    [self.navigationController pushViewController:generateVC animated:YES];
}

/**
 *  点击测试按钮
 */
- (void)testBtnClick {
    // 隐藏控件
    self.rightView.x = JMPhoneWidth;
    
    // 通知代理删除蒙版
    if ([self.delegate respondsToSelector:@selector(homeViewController:willDisPlayHideView:)]) {
        [self.delegate homeViewController:self willDismissHideView:self.promixityRightView];
    };
    
    // 跳转测试页面
    JMFrequencyViewController *freVc = [[JMFrequencyViewController alloc] init];
    [self.navigationController pushViewController:freVc animated:YES];
    freVc.title = @"测试";
}

/**
 *  点击IC按钮
 */
- (void)ICBtnClick {
    // 隐藏控件
    self.promixityRightView.x = JMPhoneWidth;
    
    // 通知代理删除蒙版
    if ([self.delegate respondsToSelector:@selector(homeViewController:willDisPlayHideView:)]) {
        [self.delegate homeViewController:self willDismissHideView:self.promixityRightView];
    }
    // 跳转拷贝页面
    JMFrequencyViewController *freVc = [[JMFrequencyViewController alloc] init];
    [self.navigationController pushViewController:freVc animated:YES];
    freVc.title = @"IC卡";
}

/**
 *  点击ID按钮
 */
- (void)IDBtnClick {
    // 隐藏控件
    self.promixityRightView.x = JMPhoneWidth;
    
    // 通知代理删除蒙版
    if ([self.delegate respondsToSelector:@selector(homeViewController:willDisPlayHideView:)]) {
        [self.delegate homeViewController:self willDismissHideView:self.promixityRightView];
    }
    
    // 跳转再生页面
    JMFrequencyViewController *IDVC = [[JMFrequencyViewController alloc] init];
    [self.navigationController pushViewController:IDVC animated:YES];
    IDVC.title = @"ID卡";
}

/**
 *  点击蓝牙卡按钮
 */
- (void)bluetoothBtnClick {
    // 隐藏控件
    self.promixityRightView.x = JMPhoneWidth;
    
    // 通知代理删除蒙版
    if ([self.delegate respondsToSelector:@selector(homeViewController:willDisPlayHideView:)]) {
        [self.delegate homeViewController:self willDismissHideView:self.promixityRightView];
    }
    
    // 跳转测试页面
    JMFrequencyViewController *freVc = [[JMFrequencyViewController alloc] init];
    [self.navigationController pushViewController:freVc animated:YES];
    freVc.title = @"蓝牙卡";
}

/**
 *  点击感应卡按钮滑出感应卡隐藏控件
 */
- (void)promixityBtnClick {
    // 通知代理添加蒙版
    if ([self.delegate respondsToSelector:@selector(homeViewController:willDisPlayHideView:)]) {
        [self.delegate homeViewController:self willDisPlayHideView:self.promixityRightView];
    }
    
    // 显示隐藏控件
    [UIView animateWithDuration:0.3 animations:^{
        self.promixityRightView.x = self.promixityBtn.x;
        self.rightView.x = JMPhoneWidth;
    }];
}

/**
 *  点击电动门遥按钮滑出电动门隐藏控件
 */
- (void)doorBtnClick {
    // 通知代理添加蒙版
    if ([self.delegate respondsToSelector:@selector(homeViewController:willDisPlayHideView:)]) {
        [self.delegate homeViewController:self willDisPlayHideView:self.rightView];
    }
    
    // 显示隐藏控件
    [UIView animateWithDuration:0.3 animations:^{
        self.rightView.x = self.doorControlBtn.x;
        self.promixityRightView.x = JMPhoneWidth;
    }];
}

/**
 *  点击汽车钥匙跳入JMCarKeyViewController
 */
- (void)carKeyBtnClick {
    // 隐藏控件
    self.rightView.x = JMPhoneWidth;
    self.promixityRightView.x = JMPhoneWidth;
    WDCarViewController * carKeyVC =[[WDCarViewController alloc]init];
   // JMCarKeyViewController *carKeyVC = [[JMCarKeyViewController alloc] init];
    [self.navigationController pushViewController:carKeyVC animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - UITabBarDelegate方法
- (void)tabBarController:(JMTabBarController *)tabBarController didDismissHomeShieldView:(UIView *)shieldView {
        [UIView animateWithDuration:0.3 animations:^{
            self.rightView.x = JMPhoneWidth;
            self.promixityRightView.x = JMPhoneWidth;
        }];
    
        [self.peripheralView removeFromSuperview];
        [self.shieldView removeFromSuperview];
        [self.connectView removeFromSuperview];
}

#pragma mark - JMCenterManagerDelegate

// 获取手机蓝牙状态
- (void)centerManager:(JMCenterManager *)centerManager didUpdateState:(CBCentralManager *)central {
    switch (central.state) {
        case CBCentralManagerStatePoweredOff: // 手机蓝牙未打开
            self.yelloBtn.hidden = NO;
            break;
        case CBCentralManagerStatePoweredOn:
            self.yelloBtn.hidden = YES;
            break;
        default:
            break;
    }
}

// 手机蓝牙打开与否
- (void)centerManager:(JMCenterManager *)centerManager phoneBlueToothIsOpend:(BOOL)opend {
    if (opend) { // 蓝牙打开
        self.yelloBtn.hidden = YES;
    } else { // 蓝牙关闭
        self.yelloBtn.hidden = NO;
        self.bluetoothBtn.selected = NO;
    }
}

// 扫描到新外设
- (void)centerManager:(JMCenterManager *)centerManager didScanNewPeripheral:(CBPeripheral *)peripheral WithAdvertisementData:(NSDictionary<NSString *,id> *)advertisementData RSSI:(NSNumber *)RSSI{
    
    // 添加外围设备
    if (![self.peripherals containsObject:peripheral] && peripheral.name != NULL) {
        [self.peripherals addObject:peripheral];
        
        // 刷新扫描的蓝牙
        [self.peripheralView.tableView reloadData];
    }

     NSString *str = [advertisementData objectForKey:@"kCBAdvDataLocalName"];
     if ([str isEqualToString:@"XXX8"]) { // ZhimaGod,XXX8
        self.mgrs.find = YES;
        [self.mgrs connectPeripheral:peripheral];
     }
}

// 连接成功
- (void)centerManager:(JMCenterManager *)centerManager didconnectPeripheral:(CBPeripheral *)peripheral {
    // 改变蓝牙按钮的状态
    self.bluetoothBtn.selected = YES;
    // 消除connectView
    [self.connectView stopAnimating];
    [self.connectView removeFromSuperview];
    // 清空外设
    [self.peripherals removeAllObjects];
    [self.peripheralView.tableView reloadData];
    // 寻找外设服务
    [self.mgrs peripheral:peripheral discoverServices:nil];
}

// 失去连接
- (void)centerManager:(JMCenterManager *)centerManager didDisconnectPeripheral:(CBPeripheral *)peripheral {
    // 改变蓝牙按钮的状态
    self.bluetoothBtn.selected = NO;
}

// 向外设发送命令
- (void)centerManager:(JMCenterManager *)centerManager canSendDataWithPeripheral:(CBPeripheral *)peripheral andCharateristic:(CBCharacteristic *)characteristic {
    Byte dataArr[] = {0x00,0x00};
    NSData * myData = [NSData dataWithBytes:dataArr length:sizeof(dataArr)];
    JMCrc16 *crc = [[JMCrc16 alloc] initWithData:myData andPort:0];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [peripheral writeValue:crc.sendData forCharacteristic:characteristic type:CBCharacteristicWriteWithResponse];
    });
}

// 处理接收到的外设数据
- (void)centerManager:(JMCenterManager *)centerManager handleReceiveDatas:(NSMutableData *)receiveDatas {
    // 拼接拷贝机软件版本号
    int headVersion = 0;
    [[receiveDatas subdataWithRange:NSMakeRange(12, 1)] getBytes:&headVersion length:sizeof(headVersion)];
    int footVersion = 0;
    [[receiveDatas subdataWithRange:NSMakeRange(13, 1)] getBytes:&footVersion length:sizeof(footVersion)];
    NSString *copySoftwareVersion = [NSString stringWithFormat:@"X-008%d.%d", headVersion,footVersion];
    
    // 存储拷贝机软件版本号
    [[NSUserDefaults standardUserDefaults] setObject:copySoftwareVersion forKey:@"copySoftwareVersion"];
    
    // 拼接拷贝机序列号
    NSString *copySerialNumber = [[NSString alloc] initWithData:[receiveDatas subdataWithRange:NSMakeRange(14, 16)] encoding:NSUTF8StringEncoding];
    
    // 存储拷贝机序列号
    [[NSUserDefaults standardUserDefaults] setObject:copySerialNumber forKey:@"copySerialNumber"];
    
    // 拼接跟新状态，0不可跟新，1可以跟新
    BOOL copyCanUpdate = NO;
    [[receiveDatas subdataWithRange:NSMakeRange(30, 1)] getBytes:&copyCanUpdate length:sizeof(copyCanUpdate)];
    NSString *copyUpdate = [NSString stringWithFormat:@"%d", copyCanUpdate];
    // 存储跟新状态
    [[NSUserDefaults standardUserDefaults] setObject:copyUpdate forKey:@"copyCanUpdate"];
}

#pragma mark - UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.peripherals.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    JMPeripheralCell *cell = [JMPeripheralCell cellWithTableView:tableView];
    CBPeripheral *peripheral = self.peripherals[indexPath.row];
    cell.peripheralLabel.text = peripheral.name;
    WDLog(@"1111");
    return cell;
}

/**
 *  选择需要连接的设备
 */
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    CBPeripheral *peripheral = self.peripherals[indexPath.row];
    // 向JMPeripheralView发送通知传送用户选择的外设名
    NSNotificationCenter *notification = [NSNotificationCenter defaultCenter];
    [notification postNotificationName:@"obtainPeripheralName" object:self.peripheralView userInfo:@{@"periphralName":peripheral.name}];
}

#pragma mark - JMPeripheralViewDelegate
/**
 *  连接用户选择的外设
 */
- (void)peripheralView:(JMPeripheralView *)peripheralView didClickedConfirmBtn:(UIButton *)confirmBtn {
    // 删除peripheralView
    [self.peripheralView removeFromSuperview];
    [self.shieldView removeFromSuperview];
    for (CBPeripheral *peripheral in self.peripherals) {
        if ([peripheral.name isEqualToString:confirmBtn.titleLabel.text]) {
            [self.mgrs connectPeripheral:peripheral];
            self.peripheral = peripheral;
            
            // 显示正在连接
            NSMutableArray *array = [[NSMutableArray alloc] initWithObjects:[UIImage imageNamed:@"loadingpic1"],[UIImage imageNamed:@"loadingpic2"],[UIImage imageNamed:@"loadingpic3"],[UIImage imageNamed:@"loadingpic4"],[UIImage imageNamed:@"loadingpic5"], [UIImage imageNamed:@"loadingpic6"],[UIImage imageNamed:@"loadingpic7"],[UIImage imageNamed:@"loadingpic8"],nil ];
            UIImageView *imageView = [[UIImageView alloc] init];
            [self.view addSubview:imageView];
            imageView.width = 250;
            imageView.height = 45;
            imageView.center = self.view.center;
            imageView.animationImages = array;
            //imageView.animationDuration = 4;
            [imageView startAnimating];
            self.connectView = imageView;
        }
    }
}

- (void)removeShieldView:(JMPeripheralView *)peripheralView {
    [self.peripheralView removeFromSuperview];
    [self.shieldView removeFromSuperview];
    if (self.mgrs.connected) {
        [JMCenterManager stopScan];
    }
}
@end
